<?php

namespace app\common\model;

use app\admin\model\Levels;
use app\api\model\Order;
use think\Db;
use think\Model;

/**
 * 会员模型
 * @method static mixed getByUsername($str) 通过用户名查询用户
 * @method static mixed getByNickname($str) 通过昵称查询用户
 * @method static mixed getByMobile($str) 通过手机查询用户
 * @method static mixed getByEmail($str) 通过邮箱查询用户
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];

    /**
     * 获取个人URL
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int $money 余额
     * @param int $user_id 会员ID
     * @param string $memo 备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int $score 积分
     * @param int $user_id 会员ID
     * @param string $memo 备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }


    /**
     * Notes: 判断是否升级等级
     * User: chenLei
     * Date: 8/25/25
     * @param $user_id
     * @return true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function upLevel($user_id)
    {
        $user = $this->where('id', $user_id)->find();

        $count = $this->xfCount($user_id);

        $level = Levels::where('buy_number', '<=', $count)->order('level desc')->find();

        if ($user->level < $level['level']) {
            $user->level = $level['level'];
            $user->save();
        }
        return true;

    }


    /**
     * Notes: 用户周期内的消费次数
     * User: chenLei
     * Date: 8/25/25
     * @param $user_id
     * @return true
     * @throws \think\Exception
     */
    public function xfCount($user_id)
    {
        $level_day = config('site.level_day');

        $start_time = strtotime('-' . $level_day . ' days');
        $end_time = time() + 84399;

        $count = ScoreLog::where('createtime', 'between time', [$start_time, $end_time])
            ->where('user_id', $user_id)
            ->where('status', ScoreLog::STATUS_XF)->count();

        return $count;
    }


    /**
     * Notes: 下次升级详情
     * User: chenLei
     * Date: 8/26/25
     * @param $user_id
     * @param $level
     * @return int|mixed|true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function nextLevelText($user_id, $level)
    {
        $data = [];

        $count = $this->xfCount($user_id);
        if ($level == 4) {
            $text = 'Keep it up to maintain your platinum';
            $diffNumber = 0;
            $data['nextLevel'] = 0;
            $data['nextNumber'] = 0;
        } else {
            $nextLevel = Levels::where('level', $level + 1)->find();
            $diffNumber = $nextLevel['buy_number'] - $count;
            $data['nextLevel'] = $nextLevel['level'];
            $data['nextNumber'] = $nextLevel['buy_number'];
            switch ($nextLevel['level']) {
                case 2:
                case 3:
                case 4:
                    $text = 'Just ' . $diffNumber . ' more times to unlock your next level tier!';
                    break;
            }
        }
        $data['count'] = $count;

        $data['text'] = $text;
        $data['diffNumber'] = $diffNumber;

        return $data;
    }


    /**
     * Notes: 查询用户当月是否生日
     * User: chenLei
     * Date: 8/26/25
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkBirthday()
    {
        $currentMonth = date('m');
        $users = Db::name('user')
            ->where("DATE_FORMAT(birthday, '%m') = :month")
            ->bind(['month' => $currentMonth])
            ->field('id,birthday')
            ->select();

        $orderModel = new Order();
        foreach ($users as $value) {
            if (!$orderModel->checkBirthdayGoods($value['id'])) {
                $orderModel->birthday($value['id']);
            }
        }

        die;
    }


    /**
     * Notes: 降级
     * User: chenLei
     * Date: 8/26/25
     * @return true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function downgrade()
    {
        $list = $this->where('level', '>', 1)
            ->field('id,level')->select();

        foreach ($list as $value) {
            $count = $this->xfCount($value['id']);
            $level = Levels::where('level', $value['level'])->find();
            if ($count < $level['buy_number']) {
                $value->level = $count - 1;
                $value->save();
            }
        }

        return true;

    }
}
